<?php


namespace App\Services;


use App\Models\Photo;

class PhotoService
{
    public function decompression($pathname){
        $pathinfo = pathinfo($pathname);
        $pathname = public_path('uploads/'.$pathname);
        $extractPath = public_path('uploads/photo/'.$pathinfo['filename']);
        if(!is_dir($extractPath)){
            mkdir($extractPath);
        }
        if(file_exists($pathname)){
            $zip = new \ZipArchive;
            $zip->open($pathname);
            $zip->extractTo($extractPath);
            $zip->close();
        }
        $data = $this->scandir($extractPath);
        $this->saveDatabase($data);
        return $data;
    }

    public function scandir($con){
        $image = app(ImageService::class);

        $filename = scandir($con);
        $path = explode('/',$con);
        $pathname = array_get($path,count($path)-1);

        $data = [];
        foreach($filename as $k=>$v){
            if($v=="." || $v==".."){
                continue;
            }
            if (strpos($v, "-50.") !== false) {
                continue;
            }
            if($v == '__MACOSX'){
                $this->deleteFolder($con.'/__MACOSX');
                continue;
            }

            $v = strtolower($v);
            if($v){
                $tmp = str_replace('_结果','',$v);

                $pin = pathinfo($tmp);
                $vk = explode('-',$pin['filename']);



                $origin_name = 'photo/'.$pathname.'/'.$v;
                $new_name = 'photo/'.$pathname.'/'.str_replace('_结果','',$v);
                rename(public_path('uploads/'.$origin_name),public_path('uploads/'.$new_name));

                if(isset($vk[1])){
                    $data[$vk[0]]['photos'][] =  $new_name;
                }else{
                    $data[$vk[0]]['cover'] =  $new_name;
                }
                $image->resize(public_path('uploads/'.$new_name),50);

            }
        }


        return $data;
    }

    public function saveDatabase($data){

        $insert = [];
        $time = date('Y-m-d H:i:s');
        foreach($data as $item){
            if(isset($item['cover']) && $item['cover']){

                $insert[] = [
                    'img'=>$item['cover'],
                    'atlas'=>json_encode(isset($item['photos'])?$item['photos']:[],256),
                    'cup'=>null,
                    'updated_at'=>$time,
                    'created_at'=>$time
                ];

            }

        }

        if($insert){
            Photo::insert($insert);
        }

    }


    function deleteFolder($folderPath) {
        if (is_dir($folderPath)) {
            $files = array_diff(scandir($folderPath), array('.', '..'));
            foreach ($files as $file) {
                $filePath = $folderPath . '/' . $file;
                is_dir($filePath) ? $this->deleteFolder($filePath) : unlink($filePath);
            }
            rmdir($folderPath);
        }
    }
}
